package cn.wolfcode.web.controller;


import cn.wolfcode.domain.Department;
import cn.wolfcode.domain.Employee;
import cn.wolfcode.domain.Role;
import cn.wolfcode.quest.EmployeeQueryObject;
import cn.wolfcode.quest.JsonResult;
import cn.wolfcode.result.PageResult;
import cn.wolfcode.service.IDepartmentService;
import cn.wolfcode.service.IEmployeeService;
import cn.wolfcode.service.IRoleService;
import cn.wolfcode.util.RequiredPermission;
import com.github.pagehelper.PageInfo;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;


import javax.servlet.annotation.MultipartConfig;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.Array;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/employee")
public class EmployeeController {
    @Autowired
    private IEmployeeService employeeService;
    @Autowired
    private IDepartmentService departmentService;
    @Autowired
    private IRoleService roleService;

    //方法显示

    @RequestMapping("/list")
    @RequiresPermissions(value = {"employee:list", "员工列表"},logical = Logical.OR)
    public String listAll(Model model, @ModelAttribute("qo") EmployeeQueryObject qo) {
        if (qo.getDeptId() == null) {
            qo.setDeptId(-1l);
        }
        Subject subject = SecurityUtils.getSubject();

        //查询出Result对象
        PageInfo<Employee> pageResult = employeeService.query(qo);
        List<Department> departments = departmentService.selectAll();

        //添加到作用域
        model.addAttribute("pageResult", pageResult);
        model.addAttribute("depts", departments);
        //跳转
        return "employee/list";
    }

    @RequestMapping("/delete")
    @ResponseBody
    @RequiredPermission(name = "员工删除", expression = "employee:delete")
    public JsonResult delete(Model model, Long id) {

        System.out.println("进入方法");
        //删除数据库中数据
            //尝试删除
            employeeService.deleteById(id);
            return new JsonResult();

    }

    @RequestMapping("/input")
    @RequiredPermission(name = "员工编辑", expression = "employee:input")
    public String input(Model model, Long id) {
        System.out.println("进入方法");
        //如果有id则查询到对应数据库中数据
        Employee employee = employeeService.get(id);

        // System.out.println(employee);
        List<Department> departments = departmentService.selectAll();
        System.out.println(departments);
        //获取角色列表
        List<Role> roles = roleService.selectAll();
        //存到作用域
        model.addAttribute("roles", roles);
        model.addAttribute("employee", employee);
        model.addAttribute("departments", departments);
        //转到input视图
        return "employee/input";
    }

    @RequiredPermission(name = "员工保存或更新", expression = "employee:saveOrUpdate")
    @RequestMapping("/saveOrUpdate")
    @ResponseBody
    public JsonResult input(Model model, Employee employee, Long[] ids) {
        //有id为修改,无id为删除
        //拿到了权限的ids,要保存到数据库中
        //如果有id,为更新
        JsonResult result = new JsonResult();
        result.setSuccess(true);
        result.setMsg("保存或者添加成功");
        try {
            if (employee.getId() != null) {
                employeeService.updateRole(employee, ids);
            } else {
                //没有id为添加
                employeeService.insertRole(employee, ids);
            }
            return result;

        } catch (Exception e) {
            e.printStackTrace();
            result.setSuccess(false);
            result.setMsg("保存或者添加失败");
            return result;

        }



      /*  //最后转到list
        return "redirect:/employee/list.do";*/
    }

    //批量删除
    @RequestMapping("/batchDelect")
    @ResponseBody
    public JsonResult batchDelect(Long[] ids) {
        JsonResult jsonResult = new JsonResult();
        jsonResult.setMsg("批量删除成功");
        jsonResult.setSuccess(true);
        try {
            if (ids != null && ids.length > 0) {
                employeeService.batchDelect(ids);
            }
            return jsonResult;
        } catch (Exception e) {
            e.printStackTrace();
            jsonResult.setMsg("批量删除失败");
            jsonResult.setSuccess(false);
            return jsonResult;
        }

    }


    //通过用户名判断用户是否存在(前端用来Jquery插件,需要返回特定的格式)
    @RequestMapping("/checkName")
    @ResponseBody
    public Map<String, Boolean> checkName(String name,Long id) {
        HashMap<String, Boolean> map = new HashMap<>();
        //当id不为空是此时是编辑操作,查看名字是否更改,更改之后的名字不能重复
         if(id!=null){
             Employee employee = employeeService.get(id);
             if(employee.getName().equals(name)){
                    map.put("valid",true);
             }else {
                 employee = employeeService.QueryByName(name);
                 map.put("valid", employee == null);
             }

             return map;
         }else {

             Employee employee = employeeService.QueryByName(name);
             map.put("valid", employee == null);
             return map;
         }

    }

    /*文件的导出功能*/
    @RequestMapping("/exportXls")
    public void exportXls(HttpServletResponse response) throws IOException {
          //设置响应头
        response.setHeader("Content-Disposition","attachment;filename=employee.xls");
        Workbook workbook=employeeService.exportXls();
        workbook.write(response.getOutputStream());

    }

    /*
          文件的导入功能
     */

    @RequestMapping("/importXls")
    @ResponseBody
    public JsonResult importXls(MultipartFile file) throws IOException {
            employeeService.importXls(file);
           return new JsonResult();
    }
     @RequestMapping("/disablea")
    public  String disable(Long id){
         Employee employee = employeeService.selectById(id);
        if(employee.isStatus()){
            employeeService.updataStatus(employee.getId(),false);
        }else {
            employeeService.updataStatus(employee.getId(),true);
        }

         return "redirect:/employee/list.do";
     }

}
